package com.servlet;

import com.dao.SqlConnection;
import com.dao.UpdateServlet;
import com.entity.Users;
import com.wf.captcha.utils.CaptchaUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/register")
public class RegisServlet extends HttpServlet {
    public SqlConnection sqlConnection = new SqlConnection();
    public UpdateServlet updateServlet = new UpdateServlet();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/Register.html").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String username = req.getParameter("username1");
        String password = req.getParameter("password2");
        String password2 = req.getParameter("password3");
        String email = req.getParameter("email");
        String captcha = req.getParameter("captcha");
        boolean ver = CaptchaUtil.ver(captcha, req);
        if ( !ver){
            CaptchaUtil.clear(req);
            System.out.println("验证码错误");
            resp.sendRedirect(req.getContextPath() + "/error");
        }else {
            // 从表单中获取的用户名和密码与预定义的用户名和密码进行比较
            if (username != null && password != null ) {
                if (password.equals(password2)){
                    Users users = sqlConnection.selectByUsernameAndPassword(username, password);
                    if (users == null){
                        try {
                            updateServlet.addSql(username,password2,email);
                            System.out.println("注册成功");
                            resp.sendRedirect(req.getContextPath() + "/index");
                        } catch (SQLException e) {
                            throw new RuntimeException(e);
                        }
                    }else {
                        System.out.println("账户已存在，请登录");
                        resp.sendRedirect(req.getContextPath() + "/login");
                    }
                }else {
                    System.out.println("两次密码不一致");
                    resp.sendRedirect(req.getContextPath() + "/error");
                }
            }
        }
    }
}
